﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FocusClock.Core
{
    public class ClockManager:IDisposable
    {
        /// <summary>
        /// 专注时间  秒
        /// </summary>
        public int FoucsTime { get; set; }
        /// <summary>
        /// 休息时间  秒
        /// </summary>
        public int RestTime { get; set; }
        /// <summary>
        /// 倒计时  秒
        /// </summary>
        public int Countdown { get; private set; }
        /// <summary>
        /// 操作类型
        /// </summary>
        public ClockActionType ActionType { get; private set; } = ClockActionType.None;
        public bool IsTimeout { get => Countdown < 0; }
        public bool IsRunning { get; private set; } = false;

        public event Action onRunning;
        public event Action onStart;
        public event Action onReset;

        private CancellationTokenSource? cancellationTokenSource = null;


        public ClockManager()
        {
            InitTask();
        }

        private void InitTask()
        {
            cancellationTokenSource = new CancellationTokenSource();
            Task.Run(() =>
            {
                do
                {
                    onTick();
                    Thread.Sleep(1000);
                } while (true);
            }, cancellationTokenSource.Token);
        }


        public void PauseOrContinue()
        {
            IsRunning = !IsRunning;
            onRunning?.Invoke();
        }



        public void Start()
        {
            if (IsRunning) return;
            ActionType = ClockActionType.Focus;
            Countdown = FoucsTime;
            IsRunning = true;
            onStart?.Invoke();
        }

        private void onTick()
        {
            if (!IsRunning) return;
            Countdown -= 1;
            onRunning?.Invoke();
        }

        public void StopFoucs()
        {
            ActionType = ClockActionType.Rest;
            Countdown = RestTime;
            IsRunning = true;
        }

        public void StopRest()
        {
            ActionType = ClockActionType.Focus;
            Countdown = FoucsTime;
            IsRunning = true;
        }

        public void Rest()
        {
            if (IsRunning) return;//非暂停状态不能重置
            ActionType = ClockActionType.Focus;
            Countdown = FoucsTime;
            IsRunning = false;
            onRunning?.Invoke();
            onReset?.Invoke();
        }

        public void Stop()
        {
            ActionType = ClockActionType.Focus;
            Countdown = FoucsTime;
            IsRunning = false;
            onRunning?.Invoke();
        }

        public void Dispose()
        {
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }
        }
    }
}
